import Vue from 'vue'
import VueRouter from 'vue-router'
const Login = () => import('../views/Login.vue')
const Layout = () => import('../components/Layout.vue')
const Index = () => import('../views/Index.vue')
const Menu = () => import('../views/menu/Index.vue')
const Role = () => import('../views/role/Index.vue')
const Admin = () => import('../views/admin/Index.vue')
const Category = () => import('../views/category/Index.vue')
const Specs = () => import('../views/specs/Index.vue')
const Goods = () => import('../views/goods/Index.vue')

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    // 嵌套路由
    children: [
      {
        path: '',
        component: Index
      },
      {
        path: 'menu',
        component: Menu,
        meta: {
          title: '菜单管理'
        }
      },
      {
        path: 'role',
        component: Role,
        meta: {
          title: '角色管理'
        }
      },
      {
        path: 'admin',
        component: Admin,
        meta: {
          title: '管理员管理'
        }
      },
      {
        path: 'category',
        component: Category,
        meta: {
          title: '商品分类'
        }
      },
      {
        path: 'specs',
        component: Specs,
        meta: {
          title: '商品规格'
        }
      },
      {
        path: 'goods',
        component: Goods,
        meta: {
          title: '商品管理'
        }
      }
    ]
  },
  {
    path: '/login',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: Login
  }
]

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
    return originalPush.call(this, location).catch(err => err)
}
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.repalce = function replace (location) { 
 return originalReplace.call(this, location).catch(err => err)
}
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})



router.beforeEach((to, from, next) => {
  document.title = to.meta.title || 'u-admin';
  // 登录的拦截，未登录时只能看login和首页（'/login'和'/'）
  let info = JSON.parse(localStorage.getItem('userInfo'));
  if (info) {
    // 登录状态下可以查看任何页面
    next()
  } else {
    // 未登录
    if (to.path === '/login' || to.path === '/') {
      // 登录页和首页不需要登录
      next()
    } else {
      // 菜单管理等页面需要登录，所以重定向到login
      next({path: '/login'});
    }
  }
})

export default router
